package com.cyzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyzy.mapper.CampusMapper;
import com.cyzy.mapper.VoteMapper;
import com.cyzy.mapper.VoteRecordMapper;
import com.cyzy.pojo.Campus;
import com.cyzy.pojo.Exhibition;
import com.cyzy.pojo.VoteRecord;
import com.cyzy.service.VoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class VoteServiceImpl extends ServiceImpl<VoteMapper, Exhibition> implements VoteService {

    @Autowired
    private VoteMapper voteMapper;

    @Autowired
    private VoteRecordMapper voteRecordMapper;
    @Autowired
    private CampusMapper campusMapper;

    @Override
    public Map<String,Object> selectAllVote(Long exhId) {
        try {
            //通过校区ID查询最近的作品展
            Exhibition exhibition = voteMapper.selectById(exhId);

            System.out.println(exhibition);

            //查询这个作品展的所有的作品Id
            // 查询对应的作品详情（图片链接，名字，作品，班级）
            HashMap<String , Object> map = new HashMap<>();
            map.put("voteList",voteMapper.selectWorkDetailByExhId(exhibition.getExhId()));
            map.put("exhId",exhibition.getExhId());
            //查询这个投票展的详情(包括投票情况,参与人数,投票总数)
            //1.查询参与人数(包括老师)
            Long participants = Long.valueOf(voteMapper.selectById(exhibition.getExhId()).getDemo2());

            System.out.println("参与人数:"+participants);
            //2.查询投票总数
            Long voteTotal = voteMapper.queryTotalVote(exhibition.getExhId());
            System.out.println("查询投票总数:"+voteTotal);
            //3.查询投票榜单
            Long voteTop = voteMapper.queryVoteTop(exhibition.getExhId());
            System.out.println("榜首的ID:"+voteTop);
            String topInfo = voteMapper.queryTopInfo(voteTop);
            System.out.println("榜首信息:"+topInfo);
            map.put("participants",participants);
            map.put("voteTotal",voteTotal);
            map.put("topInfo",topInfo);
            return map;
        }catch ( Exception e){
            log.error("查询作品列表失败", e);
            throw e;
        }
    }

    @Override
    public Boolean judgeUserVote(VoteRecord voteRecord) {
        QueryWrapper<VoteRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("exhId", voteRecord.getExhId())
                .eq("workId", voteRecord.getWorkId())
                .eq("campusId", voteRecord.getCampusId());

        if (voteRecord.getTeacherId()!=0){
            queryWrapper.eq("teacherId", voteRecord.getTeacherId());
        }
        if (voteRecord.getParentId()!=0){
            queryWrapper.eq("parentId", voteRecord.getParentId());
        }
        boolean exists = voteRecordMapper.exists(queryWrapper);
        return exists;
    }

    @Override
    public Boolean insertNewVoteRecord(VoteRecord voteRecord) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        voteRecord.setVoteTime(now.format(formatter));
        return voteRecordMapper.insert(voteRecord)>0;
    }

    @Override
    public Campus queryCampusInfo(Long campusId) {
        return campusMapper.selectById(campusId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Exhibition> queryCampusVoteInfo(Long campusId) {

        try {
            QueryWrapper<Exhibition> wrapper = new QueryWrapper<>();
            wrapper.eq("campusId",campusId);
            List<Exhibition> exhibitions = voteMapper.selectList(wrapper);
            //判断活动状态是否有没更新的

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            for (Exhibition ex :exhibitions){


                String startTIme=ex.getExhVoteStart();
                String endTIme=ex.getExhVoteEnd();
                startTIme = startTIme.trim();
                endTIme = endTIme.trim();

                LocalDate today = LocalDate.now();
                LocalDate startDate = LocalDate.parse(startTIme, formatter);
                LocalDate endDate = LocalDate.parse(endTIme, formatter);
                //判断起始时间和状态是否一致，不一致则修改状态(0:未开始 1:进行中 2:已结束)
                if (today.isBefore(startDate)) {
                    System.out.println("投票未开始");
                    //修改活动的状态
                    if (!updateVoteStatus(0, ex)){
                        throw new RuntimeException("更新状态失败");
                    }
                } else if (today.isAfter(endDate)) {
                    System.out.println("投票已结束");
                    if (!updateVoteStatus(2, ex)){
                         throw new RuntimeException("更新状态失败");
                    }
                } else {
                    System.out.println("投票进行中");
                    if (!updateVoteStatus(1, ex)){
                        throw new RuntimeException("更新状态失败");
                    }
                }
            }
            return exhibitions;
        }catch (Exception e){
            throw e;
        }
    }
    /*
     * @description: 修改活动的状态
     * @author: yangJingShi
     * @date: 2025/6/22 下午1:10
     * @param: [num, ex]
     * @return: java.lang.Boolean
     **/
    private Boolean updateVoteStatus(int num,Exhibition ex){
        if (ex.getExhStatus()!=num){
            //修改状态为未开始
            ex.setExhStatus(num);
            UpdateWrapper<Exhibition> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("exhId",ex.getExhId())
                    .set("exhStatus",num);

             if (voteMapper.update(null,updateWrapper)!=0){
                 return true;
             }else {
                 return false;
             }
        }
        return true;
    }

}
